package application

import (
	"context"
	"github.com/edgexfoundry/edgex-go/internal/app/core/metadata/container"
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	"github.com/edgexfoundry/edgex-go/internal/pkg/correlation"
	bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/container"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/errors"
)

func AutoEventAdd(deviceId string, d models.AutoEvent, ctx context.Context, dic *di.Container) (string, errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	s, err := dbClient.AutoEventAdd(deviceId, d)
	if err != nil {
		return "", err
	}
	lc.Debugf("auto event add on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return s, nil
}

func AutoEventGetByDeviceId(deviceId string, ctx context.Context, dic *di.Container) ([]models.AutoEvent, errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	events, err := dbClient.AutoEventGetByDeviceId(deviceId)
	if err != nil {
		return nil, err
	}
	lc.Debugf("auto event get by deviceId on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return events, nil
}

func AutoEventDelete(deviceId, eventId string, ctx context.Context, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.AutoEventDelete(deviceId, eventId)
	if err != nil {
		return err
	}
	lc.Debugf("auto event delete on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return nil
}

func AutoEventUpdate(deviceId string, d models.AutoEvent, ctx context.Context, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.AutoEventUpdate(deviceId, d)
	if err != nil {
		return err
	}
	lc.Debugf("auto event update on DB successfully. Correlation-id: %s ", correlation.FromContext(ctx))
	return nil
}
